import React, { useState, useEffect } from "react";
import {
  Button,
  Form,
  Input,
  Select,
  Switch,
  Table,
  Space,
  Modal,
  Tree,
  message,
} from "antd";
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  UserSwitchOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import type { TreeProps } from "antd/es/tree";
import type { ColumnsType } from "antd/es/table";
import { $get, $post } from "@/api/RestUtils";
import TimeUtils from "@/utils/TimeUtils";
import TreeUtils from "@/utils/TreeUtils";
import "./index.less";
import { useSelector } from "react-redux";

const App: React.FC = () => {
  const permissionList: string[] = useSelector((state: any) => state.permissions);

  const [searchForm] = Form.useForm();
  const [dataForm] = Form.useForm();
  const [distributeForm] = Form.useForm();

  const [infoModalShow, setInfoModalShow] = useState(false);
  const [infoModalTitle, setInfoModalTitle] = useState("");

  const [sourceModalShow, setSourceModalShow] = useState(false);
  const [checkedSourceIds, setCheckSourceIds] = useState({
    checked: [],
    halfChecked: [],
  });

  const [roleList, setRoleList] = useState([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);

  const [sourceList, setSourceList] = useState<any[]>();

  const availableList = [
    {
      available: 0,
      availableName: "锁定",
    },
    {
      available: 1,
      availableName: "正常",
    },
  ];

  let field = {
    id: "sourceId",
    parentId: "parentId"
  }

  const columns: ColumnsType<RoleDataType> = [
    {
      title: "角色名称",
      dataIndex: "roleName",
      key: "roleName",
      width: 150,
      align: "center",
    },
    {
      title: "角色编码",
      dataIndex: "roleCode",
      key: "roleCode",
      width: 150,
      align: "center",
    },
    {
      title: "状态",
      key: "action",
      width: 100,
      align: "center",
      render: (record: any) => {
        return (
          <Switch
            checked={record.available === 1}
            onClick={(checked, event) =>
              changeAvailable(checked, record.roleId)
            }
            disabled={
              !permissionList ||
              !permissionList.includes("system.role:available")
            }
          />
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "ctime",
      key: "ctime",
      width: 240,
      align: "center",
      render: (ctime: Date) => {
        return TimeUtils.format(ctime);
      },
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      align: "center",
      width: 300,
      render: (record: any) => {
        return (
          <Space size="middle">
            <Button
              type="link"
              icon={<EditOutlined />}
              size="small"
              onClick={() => switchDataModalShow(true, 1, record)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.role:update")
              }
            >
              修改
            </Button>
            <Button
              type="link"
              icon={<UserSwitchOutlined />}
              size="small"
              onClick={() => switchSourceModalShow(true, record.roleId)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.role:distribute")
              }
            >
              分配资源
            </Button>
            <Button
              type="link"
              icon={<DeleteOutlined />}
              size="small"
              onClick={() => deleteRoleConfirm(record.roleId)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.role:delete")
              }
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    getSourceList();
    search(currentPage, 10);
  }, []);

  const getSourceList = () => {
    $get("/source/find", null)
      .then((res: any) => {
        if (res.code === 0) {
          let sourceList = TreeUtils.list2Tree(res.data, field);
          setSourceList(sourceList);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const switchDataModalShow = (show: boolean, model: number, formData: any) => {
    setInfoModalShow(show);
    if (model === 0) {
      // 新增
      setInfoModalTitle("新增角色信息");
    } else {
      // 修改
      setInfoModalTitle("修改角色信息");
      dataForm.setFieldsValue(formData);
    }
  };

  const switchSourceModalShow = (show: boolean, roleId?: number) => {
    setSourceModalShow(show);
    if (show) {
      distributeForm.setFieldValue("roleId", roleId);
      let param = {
        roleId: roleId,
      };
      // 查询当前role的所有资源
      $get("/source/getSourceIdListByRoleId", param)
        .then((res: any) => {
          if (res.code === 0) {
            setCheckSourceIds({ checked: res.data, halfChecked: [] });
          } else {
            message.error(res.msg);
          }
        })
        .catch((err: any) => {
          message.error("系统异常");
        });
    } else {
      distributeForm.resetFields();
      setCheckSourceIds({ checked: [], halfChecked: [] });
    }
  };

  const closeModal = () => {
    setInfoModalShow(false);
    resetDataForm();
  };

  const saveOrUpdate = (formData: any) => {
    let url;
    if (formData.roleId != null) {
      url = "/role/update";
    } else {
      url = "/role/save";
    }
    $post(url, formData)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          setCurrentPage(1);
          search(1, 10);
          closeModal();
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const distribute = (formData: any) => {
    formData.sourceIdList = checkedSourceIds.checked;
    $post("/role/distribute", formData)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          setCurrentPage(1);
          search(1, 10);
          switchSourceModalShow(false);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const changeAvailable = (checked: boolean, roleId: number) => {
    let available = checked ? 1 : 0;
    let param = {
      roleId: roleId,
      available: available,
    };
    $post("/role/update", param)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          setCurrentPage(1);
          search(1, 10);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const deleteRole = (roleId: number) => {
    let param = {
      roleId: roleId,
    };
    $get("/role/delete", param)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          setCurrentPage(1);
          search(1, 10);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const deleteRoleConfirm = (roleId: number) => {
    Modal.confirm({
      title: "是否删除当前角色？",
      icon: <ExclamationCircleFilled />,
      okText: "是",
      cancelText: "否",
      onOk() {
        deleteRole(roleId);
      },
    });
  };

  const renderAvailable = () => {
    let options = availableList.map((option: any) => {
      return { label: option.availableName, value: option.available };
    });
    return <Select options={options} placeholder="角色状态" />;
  };

  const search = (pageNum: number, pageSize: number) => {
    let param = {
      pageNum: pageNum,
      pageSize: pageSize,
      ...searchForm.getFieldsValue(),
    };
    $get("/role/findByPage", param)
      .then((res: any) => {
        if (res.code === 0) {
          let roleList = res.data.list.map((item: any) => {
            return {
              key: item.roleId,
              ...item
            }
          })
          setRoleList(roleList);
          setTotal(res.data.total);
          setCurrentPage(pageNum);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const resetDataForm = () => {
    dataForm.resetFields();
  };

  const resetSearchForm = () => {
    searchForm.resetFields();
  };

  const checkSource: TreeProps["onCheck"] = (checkedKeys: any) => {
    setCheckSourceIds(checkedKeys);
  };

  return (
    <>
      <Modal
        title="分配资源"
        open={sourceModalShow}
        closable={true}
        onCancel={() => switchSourceModalShow(false, 0)}
        footer={null}
      >
        <Form
          form={distributeForm}
          labelAlign="right"
          layout="vertical"
          colon={false}
          onFinish={distribute}
        >
          <Form.Item name="roleId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item name="sourceIdList">
            <Tree
              checkable
              checkStrictly
              showLine
              defaultExpandAll={true}
              checkedKeys={checkedSourceIds}
              onCheck={checkSource}
              fieldNames={{
                title: "sourceName",
                key: "sourceId",
                children: "children",
              }}
              treeData={sourceList}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={infoModalTitle}
        open={infoModalShow}
        closable={true}
        onCancel={closeModal}
        footer={null}
      >
        <Form
          form={dataForm}
          labelAlign="right"
          layout="vertical"
          colon={false}
          onFinish={saveOrUpdate}
        >
          <Form.Item name="roleId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            name="roleName"
            label="名称"
            rules={[
              { required: true, type: "string", message: "请输入角色名称" },
              { min: 2, max: 12, message: "长度在2~12位之间" },
            ]}
          >
            <Input placeholder="角色名称" />
          </Form.Item>
          <Form.Item
            name="roleCode"
            label="标识"
            rules={[
              { required: true, type: "string", message: "请输入角色名称" },
              { min: 2, max: 16, message: "长度在2~16位之间" },
            ]}
          >
            <Input placeholder="角色标识" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            <Button onClick={resetDataForm}>重置</Button>
          </Form.Item>
        </Form>
      </Modal>
      <div className="role-body">
        <div className="search-condition">
          <Form
            form={searchForm}
            labelAlign="left"
            name="horizontal_login"
            colon={false}
          >
            <div className="form-body">
              <Form.Item name="roleName" label="角色名称">
                <Input placeholder="角色名称" maxLength={12} />
              </Form.Item>
              <Form.Item name="roleCode" label="角色编码">
                <Input placeholder="角色编码" maxLength={16} />
              </Form.Item>
              <Form.Item name="available" label="状态">
                {renderAvailable()}
              </Form.Item>
            </div>
            <div className="form-footer">
              <Form.Item>
                <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  onClick={() => search(1, 10)}
                >
                  查询
                </Button>
                <Button icon={<ReloadOutlined />} onClick={resetSearchForm}>
                  重置
                </Button>
              </Form.Item>
            </div>
          </Form>
        </div>
        <div className="table-area">
          <div className="operate-btn-group">
            <Button
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => switchDataModalShow(true, 0, null)}
              disabled={
                !permissionList || !permissionList.includes("system.role:save")
              }
            >
              新增
            </Button>
          </div>
          <div className="table-data">
            <Table
              dataSource={roleList}
              columns={columns}
              scroll={{ x: 1200 }}
              pagination={{
                current: currentPage,
                total: total,
                onChange: search,
              }}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default App;
